package cl.mt.proxy;

import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import cl.mt.data.DataPerfil;
import cl.mt.dto.DTOPerfil;

public class ProxyPerfil implements Serializable {

	private static final long serialVersionUID = 1L;
	private transient Logger log = LogManager.getLogger(ProxyPerfil.class.getName());

	private static ProxyPerfil instance = null;
	private static Collection<DTOPerfil> lista = null;

	public ProxyPerfil() {
	}

	public static ProxyPerfil getInstance() {
		if (instance == null) {
			instance = new ProxyPerfil();
		}
		return instance;
	}

	public DTOPerfil getById(Integer id) {
		if (id == null)
			return null;
		if (lista == null)
			findAll();

		if (lista != null)
			for (Iterator<DTOPerfil> it = lista.iterator(); it.hasNext();) {
				DTOPerfil dto = it.next();
				if (id.equals(dto.getId()))
					return dto;
			}

		return null;
	}

	public String getNombre(Integer id) {
		if (id == null)
			return null;
		if (lista == null)
			findAll();

		if (lista != null)
			for (Iterator<DTOPerfil> it = lista.iterator(); it.hasNext();) {
				DTOPerfil dto = it.next();
				if (id.equals(dto.getId()))
					return dto.getNombre();
			}

		return null;
	}

	private void findAll() {
		DataPerfil dao = new DataPerfil();
		lista = dao.findAll();
		log.debug("Cargando Todos los Registros");
	}

	public void refresh() {
		lista = null;
		log.debug("Refresh Proxy");
	}

	public Collection<DTOPerfil> getLista() {
		if (lista == null)
			findAll();
		return lista;
	}
}
